package com.obtk.property.controller;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Timer;
import java.util.TimerTask;

@Controller
public class SendController {
    @RequestMapping("/sendSMS")
    public void SendSMS(HttpServletRequest request, HttpServletResponse response) {
        HttpClient client = new HttpClient();
        //当然可以使用其他的接口，这里我们直接利用现成的短信接口就好了
        PostMethod method = new PostMethod("http://106.ihuyi.com/webservice/sms.php?method=Submit");
//设置短信内容的编码格式(编码格式为 UTF-8，支持 300 个字的长短信，长短信 按多条计费)
        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");
//验证码(变量)
        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
//发送的短信的内容
        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "C77921733"), //查看用户名 登录用户中心->验证码通知短信>产品总览->API接口信息->APIID
                new NameValuePair("password", "cd76a2c7638df89c775fe118f5759183"), //查看密码 登录用户中心->验证码通知短信>产品总览->API接口信息->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", "19047857068"),//我们要通过接口将短信发送给哪个手机号
                new NameValuePair("content", content),//不需要关心
        };
        //设置方法请求体内容
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String SubmitResult = method.getResponseBodyAsString();
            //System.out.println(SubmitResult);
            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();
            String code = root.elementText("code");//返回值为2时，表示提交成功
            String msg = root.elementText("msg");//当提交成功后，此字段为流水号，否则为0
            String smsid = root.elementText("smsid");//提交结果描述

            System.out.println(code);
            System.out.println(msg);
            System.out.println(smsid);

            if ("2".equals(code)) {
                System.out.println("短信提交成功");
            }


            // 将数据存入session
            request.getSession().setAttribute("checkCode", mobile_code);

            request.getSession().setAttribute("createTime", System.currentTimeMillis());
            // 将验证码生成时间存入session，若超过五分钟则不通过校验
            // 将验证码生成时间存入session，若超过五分钟则不通过校验
            final HttpSession session = request.getSession();
            try {
                // Timer 和 TimerTask都是java.util包下
                final Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        session.removeAttribute("checkCode");
                        System.err.println("checkCode删除成功");
                        timer.cancel();
                    }
                }, 5 * 60 * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
        // 验证码检测
    @RequestMapping("/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=utf8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String checkCode = request.getParameter("checkCode");
        String code = String.valueOf(session.getAttribute("checkCode"));
        if (checkCode.equals(code)) {
            //验证码使用成功后，从session删除
            request.getSession().removeAttribute("checkCode");
            out.print("验证码正确");
        } else {
            out.print("验证码错误");
        }
    }

}
